﻿using Prism.Events;
using Prism.Ioc;
using Module.Common.Common;
using Module.Common.PubEvent;
using Module.Common.Views.Marks;
using System.Windows.Controls;
using System.Windows;
using Module.Common.Views;
using System.Data;
using Module.Common.Properties;
using ServiceItem;
using ServiceItem.Engine;
using Module.Common.Interface;

namespace Module.CanJuPoJie.Views
{
    /// <summary>
    /// Interaction logic for CanJuPoJie
    /// </summary>
    public partial class CanJuPoJieApp : UserControl
    {
        private readonly IEventAggregator Ea;
        private static DataTable CanJuData;
        private ChessBoard board;
        public int CanJuIndex { get; set; }

        public CanJuPoJieApp(IEventAggregator ea, IContainerProvider Cp, LastLocation lastLocation, CurrentLoaction currentLoaction)
        {
            InitializeComponent();
            this.Ea = ea;
            CanJuIndex = Settings.Default.CanJuIndex;

            var sqliteHelper = Cp.Resolve<SqliteHelper>();
            CanJuData = sqliteHelper.Select("CanJuKu", "rowid,*");
            board = new(ea, Cp, lastLocation, currentLoaction, this.GetType().Module.Name);
            ChessBoardRegion.Children.Add(board);
            ReStart();
        }
        public void ReStart()
        {
            string fen = CanJuData.Rows[CanJuIndex]["FENstring"].ToString();
            board.SetPieceOnAssignInitPosition(fen);
            //CanJuComment.Text = $"第{CanJuIndex + 1}局/共{CanJuData.Rows.Count}局{System.Environment.NewLine}【{CanJuData.Rows[CanJuIndex]["Name"].ToString()}】：{System.Environment.NewLine}{CanJuData.Rows[CanJuIndex]["Comment"].ToString()}";
            CanJuComment.Text = $"{CanJuIndex + 1}/{CanJuData.Rows.Count}";
            Ea.GetEvent<ModuleMessageEvent>().Publish(new ModuleMessage()
            {
                MessageName = "reStart",
                SenderFrom = this.GetType().Name,
                Content = "重新开局",
                ModuleName= this.GetType().Module.Name,
            });
        }


        private void PreCanJu(object sender, RoutedEventArgs e)
        {
            CanJuIndex--;
            if (CanJuIndex < 0) CanJuIndex = 0;
            Settings.Default.CanJuIndex = CanJuIndex;
            Settings.Default.Save();
            ReStart();
        }

        private void NextCanJu(object sender, RoutedEventArgs e)
        {
            CanJuIndex++;
            if (CanJuIndex >= CanJuData.Rows.Count) CanJuIndex = CanJuData.Rows.Count - 1;
            Settings.Default.CanJuIndex = CanJuIndex;
            Settings.Default.Save();
            ReStart();
        }

        private void ReStartCanJu(object sender, RoutedEventArgs e)
        {
            ReStart();
        }
    }
}
